package com.zzyl.framework.interceptor;

import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 小程序端Token校验拦截器
 *
 * @Author mr.wu
 * @Date 2025-5-25 8:51
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 拦截逻辑
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result  = handler instanceof HandlerMethod;
        //针对非控制器资源直接放行
        if (!result){
            return true;
        }

        //1. 获取请求头中的Token
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);

        //2. 如果Token为空则响应401
        if(StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("非法token，请登录");
        }

        //3. 解析Token
        try {
            Claims claims = tokenService.parseToken(token);

            //5. 如果解析成功，获取用户ID设置到ThreadLocal中
            Object userIdObj = claims.get("userId");
            Long userId = Long.valueOf(String.valueOf(userIdObj));
            UserThreadLocal.set(userId);
        } catch (Exception e) {
            e.printStackTrace();
            //4. 如果解析失败则响应401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            throw new RuntimeException("非法token，请登录");
        }
        //6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
